import re
import json
from rest_framework import serializers
from django.contrib.auth import get_user_model
from rest_framework_jwt.settings import api_settings
from .models import AliUser
from .client import AliPayClient
from apps.user_operation.models import LevelDesc
from finance_c2c.local_settings import AliPayPrams
from finance_c2c.settings import REGEX_MOBILE
from apps.user_operation.utils import jwt_payload_handler

# from core.tools.encryption import hashlib_md5
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
UserModel = get_user_model()
ali_pay_client = AliPayClient(AliPayPrams.get("appid"), private_key=AliPayPrams.get("private_key"),
                              public_key=AliPayPrams.get("public_key"), encrypt_key=AliPayPrams.get("encrypt_key"),
                              ali_public_key=AliPayPrams.get("ali_public_key"))


class AliUserSerializers(serializers.ModelSerializer):
    city = serializers.CharField(write_only=True, required=False, allow_blank=True, allow_null=True, label="城市")
    province = serializers.CharField(write_only=True, required=False, allow_blank=True, allow_null=True, label="省份")
    head_url = serializers.CharField(write_only=True, required=False, allow_blank=True, allow_null=True, label="头像")
    code = serializers.CharField(write_only=True, required=True, allow_blank=False, allow_null=False, label="code")
    mobile = serializers.CharField(label="手机号", required=True, allow_null=False, allow_blank=True)

    class Meta:
        model = AliUser
        fields = ("city", "province", "head_url", "code", "mobile")

    def validate_mobile(self, mobile):
        response = ali_pay_client.decrypt_content(mobile, "AES")
        result = json.loads(response)
        code = result.get("code")
        mobile = result.get("mobile")
        if code == "10000":
            if re.match(REGEX_MOBILE, mobile):
                return mobile
            else:
                raise serializers.ValidationError("无效的手机号")
        else:
            raise serializers.ValidationError("手机号获取错误")

    def validate(self, attrs):
        code = attrs.pop("code")
        response = ali_pay_client.outh.fetch_oauth_token(code)
        alipay_system_oauth_token_response = response.get("alipay_system_oauth_token_response")
        user_id = alipay_system_oauth_token_response.get("user_id")
        if user_id:
            attrs["ali_user_id"] = user_id
            self.create(attrs)
            return attrs
        else:
            raise serializers.ValidationError(alipay_system_oauth_token_response.get("sub_msg"))

    def create(self, validated_data):
        instance = super(AliUserSerializers, self).create(validated_data)
        mobile = instance.mobile
        try:
            user = UserModel.objects.get(mobile=mobile)
        except UserModel.DoesNotExist as e:
            user = UserModel.objects.create(
                mobile=mobile,
                level=LevelDesc.objects.get(level=1),
                username=mobile,
            )
            user.ali_user = user
            user.save()
        payload = jwt_payload_handler(self, user)
        token = jwt_encode_handler(payload)
        setattr(self, 'object', {"user": user, "token": token})
        return user
